package com.editso.haier.util;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 *
 * 对uri的功能提高
 * */
public final class XUri{
    private final URI uri;
    private final Map<String, Object> query = new HashMap<>();

    public XUri(URI uri) {
        this.uri = uri;
        parseQuery();
    }

    private void parseQuery(){
        String sQuery = uri.getQuery();
        String[] strings = sQuery.split("&");
        String[] queryMap = null;
        for (String s : strings) {
            queryMap = s.split("=");
            if (queryMap.length == 2){
                query.put(queryMap[0], queryMap[1]);
            }else if (queryMap.length == 1){
                query.put(queryMap[0], null);
            }
        }
    }

    public String getQuery(String name){
        return Objects.requireNonNull(query.get(name)).toString();
    }

    public int getQueryInt(String name){
        return Integer.parseInt(getQuery(name));
    }

    public double getQueryDouble(String name){
        return Double.parseDouble(getQuery(name));
    }

    public boolean getQueryBoolean(String name){
        return Boolean.getBoolean(getQuery(name));
    }

    public String getHost(){
        return uri.getHost();
    }

    public String getScheme(){
        return uri.getScheme();
    }

    public int getPort(){
        return uri.getPort();
    }

    public String getPath(){
        return uri.getPath();
    }

    public String getUserInfo(){
        return uri.getUserInfo();
    }

    public URI getUri() {
        return uri;
    }

    public static XUri parse(String uri){
        return from(URI.create(uri));
    }

    public static XUri from(URI uri){
        return new XUri(uri);
    }

    @Override
    public String toString() {
        return uri.toString();
    }
}
